package org.jivesoftware.webchat.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Random;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.jivesoftware.webchat.ChatManager;
import org.jivesoftware.webchat.settings.ConnectionSettings;

/**
 * Servlet implementation class for Servlet: UploadServlet
 * 
 */
public class UploadServlet extends HttpServlet implements Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	File tmpDir = null;// 初始化上传文件的临时存放目录
	File saveDir = null;// 初始化上传文件后的保存目录
	String host = null; 

	public UploadServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		final String _workgroup = request.getParameter("workgroup");
		final String workgroup = "workgroup_" + _workgroup.substring(0, _workgroup.lastIndexOf("@"));
//		final String chatID = request.getParameter("chatID");
		final String userNickname = request.getParameter("userNickname");
		

        StringBuilder sb = new StringBuilder(getServletContext().getRealPath("files"));
        sb.append(File.separatorChar);
        sb.append(workgroup);
        sb.append(File.separatorChar);
        sb.append("tmp");
        sb.append(File.separatorChar);
        String tmpPath = sb.toString();

        tmpDir = new File(tmpPath);
		if (!tmpDir.isDirectory()){
			tmpDir.mkdirs();
		}

        sb = new StringBuilder(getServletContext().getRealPath("files"));
        sb.append(File.separatorChar);
        sb.append(workgroup);
        sb.append(File.separatorChar);
        sb.append(userNickname);
        sb.append(File.separatorChar);
		String destPath = sb.toString();
		
		saveDir = new File(destPath);
		if (!saveDir.isDirectory()) {
			saveDir.mkdirs();
		}
		try {
			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory dff = new DiskFileItemFactory();// 创建该对象
				dff.setRepository(tmpDir);// 指定上传文件的临时目录
				dff.setSizeThreshold(1024000);// 指定在内存中缓存数据大小,单位为byte
				ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
				sfu.setFileSizeMax(5000000);// 指定单个上传文件的最大尺寸
				sfu.setSizeMax(10000000);// 指定一次上传多个文件的总尺寸
				FileItemIterator fii = sfu.getItemIterator(request);// 解析request
				
				
				// 请求,并返回FileItemIterator集合
				while (fii.hasNext()) {
					FileItemStream fis = fii.next();// 从集合中获得一个文件流
					if (!fis.isFormField() && fis.getName().length() > 0) {// 过滤掉表单中非文件域
						// 获得上传文件的文件名
				        String originalFileName = fis.getName();
				        byte[] byte_originalName = originalFileName.getBytes("UTF-8");
				        String originalName = new String(byte_originalName, "UTF-8");
				        
				        String extName = originalName.substring(originalName.indexOf(".") + 1);

				        String newFileName = getOutputFileName(extName);
				        
						BufferedInputStream in = new BufferedInputStream(fis.openStream());// 获得文件输入流
						BufferedOutputStream out = new BufferedOutputStream(
								new FileOutputStream(new File(destPath + newFileName)));// 获得文件输出流
						Streams.copy(in, out, true);// 开始把文件写到你指定的上传文件夹
						// <html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
						sb.setLength(0);
//						sb.append("<script type='text/javascript'>parent.uploadFileDone('http://")
//							.append(host).append(":8088")
//							.append("/webchat/files/")
//							.append(workgroup).append("/")
//							.append(userNickname).append("/")
//							.append(newFileName)
//					        .append("', '").append(originalName).append("');</script>");

						sb.append("<script type='text/javascript'>parent.").append(Config.getMethod()).append("('")
							.append(Config.getFileDownloadPath())
							.append(workgroup).append("/")
							.append(userNickname).append("/")
							.append(newFileName)
					        .append("', '").append(originalName).append("');</script>");
						// </head><body></body></html>
						String rsp = sb.toString();
						System.err.println(rsp);
						response.getWriter().println(rsp);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init() throws ServletException {
		/*
		 * 对上传文件夹和临时文件夹进行初始化
		 */
		super.init();
//		String tmpPath = "d:/tmpdir/";
//		String savePath = "d:/updir/";
//		tmpDir = new File(tmpPath);
//		saveDir = new File(savePath);
//		if (!tmpDir.isDirectory())
//			tmpDir.mkdir();
//		if (!saveDir.isDirectory())
//			saveDir.mkdir();

		ChatManager chatManager = ChatManager.getInstance();
        ConnectionSettings settings = chatManager.getChatSettingsManager().getSettings();
        host = settings.getServerDomain();
	}

    public String getOutputFileName(String extName) {
        StringBuilder sb = new StringBuilder();
        sb.append("file");
        Calendar cal = Calendar.getInstance();
        sb.append(cal.get(Calendar.HOUR_OF_DAY));
        sb.append('-');
        sb.append(cal.get(Calendar.MINUTE));
        sb.append('-');
        sb.append(cal.get(Calendar.SECOND));
        sb.append('-');
        sb.append(getRandomString(6));
        sb.append(".");
        sb.append(extName);
        String fileName = sb.toString();
        return fileName;
    }
    
    private String getRandomString(int length) { 
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < length; i++) {   
            int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
     }
}